package xdu.lz.pc;

public class Code01_SimplePC {

    public static void main(String[] args) throws Exception {
        Code01_SimplePC pc = new Code01_SimplePC();
        new Thread(()->{
            try {
                pc.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                pc.consume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private final Object LOCK = new Object();

    private boolean isProduced = false;

    private int counter = 0;

    public void produce() throws InterruptedException {

        while (true) {
            synchronized (LOCK) {
                if (isProduced) {
                    LOCK.wait();
                } else {
                    System.out.println(Thread.currentThread().getName() + "生产了:" + (++counter));
                    isProduced = true;
                    LOCK.notifyAll();
                    Thread.sleep(10);
                }
            }
        }
    }

    public void consume() throws InterruptedException {
        while (true) {
            synchronized (LOCK) {
                if (!isProduced) {
                    LOCK.wait();
                } else {
                    System.out.println(Thread.currentThread().getName() + "消费了:" + (counter));
                    isProduced = false;
                    LOCK.notifyAll();
                    Thread.sleep(10);
                }
            }
        }
    }
}
